import {Component, Input, OnInit} from '@angular/core';
import {Employee} from '../employee.type';
import {EmployeeService} from '../employee.service';
import {HttpResponse} from "@angular/common/http"
import {NzMessageService} from 'ng-zorro-antd/message';
import {FormGroup} from "@angular/forms";

//组件装饰器
@Component({
  selector: 'app-employee-list', //选择器，指定在HTML中使用此组件的方式
  templateUrl: './employee-list.component.html', //模板的URL路径，用于渲染组件的视图
  styleUrl: './employee-list.component.scss' //样式文件URL路径，用于定义组件的样式
})

/**
 * 员工列表组件类
 */
export class EmployeeListComponent implements OnInit {

  constructor(private employeeService: EmployeeService,  //员工服务，用于调用员工服务
              private nzMessageService: NzMessageService //消息服务，用于显示消息提示框
  ) {
  }

  //初始化时执行查询操作
  ngOnInit() {
    this.query();
  }

  employeesList: Employee[] = [] //员工列表数组
  pageNum: number = 1  //当前页码
  pageSize: number = 5 //每页显示条数
  total: number = 0    //总记录数
  loading: boolean = false //加载状态
  editVisible: boolean = false //编辑模态框可见性
  employeeId: number = 0 //当前选中的员工ID

  editData: any //编辑数据
  name: string = ''   //查询条件：姓名
  gender: string = '' //查询条件：性别

  //分页条件查询
  query() {
    this.loading = true //设置加载状态为true，表示开始加载数据
    this.employeeService.page(this.pageNum, this.pageSize, this.name, this.gender).subscribe((res: HttpResponse<Employee[]>) => {
      // @ts-ignore
      this.total = +res.body.data.totalRow //获取响应体中的总记录数
      // @ts-ignore
      this.employeesList = res.body.data.records //获取响应体中的当前页数据
      this.loading = false //加载完成，设置加载状态为false
    });
  }

  //删除
  del(id: number) {
    this.employeeService.remove(id).subscribe(res => {
      this.nzMessageService.success('删除成功')
      this.query() //重新查询以更新数据
    })
  }

  //取消删除
  cancelDel() {
    this.nzMessageService.info('取消删除')
  }

  //弹出编辑模态框
  showEditModel(id: number) {
    this.editVisible = true
    //根据ID获取员工数据
    this.employeeService.getById(id).subscribe((employee: any) => {
      this.editData = employee.data
      this.employeeId = employee.data.id
      //对表单数据进行回显
      this.editData.patchValue(employee)
    })
  }

  //更新员工信息
  updateList(data: Employee) {
    this.editVisible = false
    if (!Object.keys(data)) return //如果传入的员工数据为空，则直接返回，不执行任何操作
    this.query() //重新查询以更新数据
  }

  //重置查询条件，并重新进行查询
  clear() {
    this.name = ''
    this.gender = ''
    this.pageNum = 1
    this.pageSize = 5
    this.query()
  }
}
